//
//  RunLoopPlayScrollView.m
//  DSYWangyi
//
//  Created by dllo on 16/1/25.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "RunLoopPlayScrollView.h"
#import <UIImageView+WebCache.h>
#import "DSYCarouselModel.h"

@interface RunLoopPlayScrollView ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) NSTimeInterval second;  /**< 轮播的时间元 */

@property (atomic, assign) BOOL canDrag;

@end

@implementation RunLoopPlayScrollView



- (instancetype)initWithFrame:(CGRect)frame playSource:(NSArray *)source
{
    self = [super initWithFrame:frame];
    if (self) {
        self.playSource = [NSArray arrayWithArray:source];
        
        if (_second != 1) {
            
            _second = 1;
        }
        
        // 轮播图片的创建
        [self createImages];
    }
    return self;
}



// scrollView的getter方法
- (UIScrollView *)scrollView
{
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.backgroundColor = [UIColor redColor];
        
        [self addSubview:_scrollView];
        
        // 取消弹簧效果
        _scrollView.bounces = NO;
        
        // 取消滚动条显示
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        
        // 设置代理
        self.scrollView.delegate = self;
        
        if (_playSource.count <= 3) {
            self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 0);
        } else {
            
            self.scrollView.contentSize = CGSizeMake((_playSource.count + 2) * SCREEN_WIDTH, 0);
        }
        // 设置分页效果
        _scrollView.pagingEnabled = YES;
        
    }
    return _scrollView;
}

// 属性的getter方法
- (UIPageControl *)pageControl
{
    if (_pageControl == nil && _playSource.count > 3) {
        // 分页控件
        self.pageControl = [[UIPageControl alloc] init];
        // 总页数
        _pageControl.numberOfPages = _playSource.count - 2;
        // 控件的尺寸
        CGSize size = [_pageControl sizeForNumberOfPages:_playSource.count];
        _pageControl.frame = CGRectMake(0, 0, size.width, size.height);
        _pageControl.center = CGPointMake(self.center.x, self.bounds.size.height - 20);
        
        // 相关颜色的设置
        _pageControl.pageIndicatorTintColor = [UIColor redColor];
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
        _pageControl.backgroundColor = [UIColor clearColor];
        
        // 添加到scroll的父视图上
        [self addSubview:_pageControl];
        
        // 添加监听方法
        [_pageControl addTarget:self action:@selector(pageChanged:) forControlEvents:UIControlEventValueChanged];
        
    }
    return _pageControl;
}



- (void)createImages {
    
    
    // 设置图片
    for (int i = 0; i < _playSource.count; i++) {

        UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.scrollView.bounds];
        // 开启imageView的用户交互功能
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clicked:)];
        [imageView addGestureRecognizer:tap];

        // 取出model
        DSYCarouselModel *model = (DSYCarouselModel *)_playSource[i];
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
        [_scrollView addSubview:imageView];
    }
    
    
    // 计算出imageView的位置
    [_scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIImageView * _Nonnull imageView, NSUInteger idx, BOOL * _Nonnull stop) {
       
        // 调整x  -> origin->frame
        CGRect frame = imageView.frame;
        frame.origin.x = idx * frame.size.width;
        
        imageView.frame = frame;
    }];
    
    // 分页初始页数为0
    self.pageControl.currentPage = 0;
    [self pageChanged:_pageControl];
    
    // 启动始终
//    [self startTimer];
}

- (void)startTimer {
    
    
    self.timer = [NSTimer timerWithTimeInterval:_second target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
    
    // 添加到运行循环中
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

- (void)updateTimer {
    
    // 页号发生变化
    // (当前页数 + 1) % 总页数
    NSInteger page = (self.pageControl.currentPage + 1);
    
    if (page <= _playSource.count - 3) {
//        _scrollView.contentOffset = CGPointMake(page * SCREEN_WIDTH, 0);
    }
    
    if (page >= _playSource.count - 2) {
        _scrollView.contentOffset = CGPointMake(0, 0);
    
        page = 0;
    }
    
    self.pageControl.currentPage = page;
    
    // 调用监听方法，让scrollView滚动
    [self pageChanged:self.pageControl];
    
}



// 分页控件的监听方法
- (void)pageChanged:(UIPageControl *)page {
    
    // 根据页数去调整scrollView上的图片位置的contentOffset
    CGFloat x = (page.currentPage + 1) * self.scrollView.bounds.size.width;
    [UIView animateWithDuration:0.5 animations:^{
        _scrollView.contentOffset = CGPointMake(x, 0);
    }];
}


#pragma mark - scrollViewDeleg方法
// 当scrollView被拖拽时
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 停止时钟，停止之后就不能再使用，如果重启时钟，就需要重实例化
    [self.timer invalidate];
    
}


// 当scrollView被拖拽结束时
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    // 又重新开始自己的轮播
    [self startTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 获取scrollView的偏移量
    
    CGFloat x = _scrollView.contentOffset.x;

    // 当偏移量大于图片数组的_playSource.count - 1
    if (x >= (_playSource.count - 1) * SCREEN_WIDTH) {
        [UIView animateWithDuration:0.00001 animations:^{
            
            _pageControl.currentPage = 0;
            
        }];
    } else if (x < SCREEN_WIDTH) {
        _pageControl.currentPage = _playSource.count - 1;
    } else {
        _pageControl.currentPage = (NSInteger)(x / SCREEN_WIDTH) - 1;
    }
    [self pageChanged:_pageControl];

}


    

// 供外部调用
- (void)startPlay
{
    [self startTimer];
}

- (void)stopPlay
{
    [self.timer invalidate];
}

// 设置轮播每一张图片的时间
- (void)setTimerWithTimeInterval:(NSTimeInterval)second
{
    self.second = second;
}

#pragma mark - 点击方法
- (void)clicked:(UITapGestureRecognizer *)tap {
    
    NSInteger index = (NSInteger)(_scrollView.contentOffset.x / _scrollView.frame.size.width);
    DSYCarouselModel *model = _playSource[index];

    if (index < 1) {
        return;
    }

    UINavigationController *nav = [self getViewController];
        if ([model.action_type integerValue] == 1) {
        WEBViewController *web = [[WEBViewController alloc] init];
        web.url = model.action_value;
        web.hidesBottomBarWhenPushed = YES;
        [nav pushViewController:web animated:YES];
    }
    
    if ([model.action_type integerValue] == 19) {
        
        if ([model.isExclusive integerValue] == 1) {
            
            BYJCarousViewController1 *VC = [[BYJCarousViewController1 alloc] init];
            VC.value = model.action_value;
            [nav pushViewController:VC animated:YES];
            
          }
    }
    
    if ([model.action_type integerValue] == 5) {
        BYJCarouselViewController *VC = [[BYJCarouselViewController alloc] init];
        VC.value = model.action_value;
        [nav pushViewController:VC animated:YES];
    }
    
    
}


// 获取当前navigation
- (UINavigationController*)getViewController {
    
    for (UIView* next = [self superview];next; next = next.superview) {
        
        UIResponder* nextResponder = [next nextResponder];
        
        if ([nextResponder isKindOfClass:[UINavigationController class]]) {
            
            return (UINavigationController *)nextResponder;
            
        }
        
    }
    return nil;
}


@end
